package com.mlkj.ytdc.modules;

import android.content.Context;
import android.media.AudioManager;
import android.os.Build;

import androidx.annotation.NonNull;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.mlkj.ytdc.utils.Event;

/**
 * 音量管理
 */
public class AudioManage extends ReactContextBaseJavaModule {
    public AudioManage(@NonNull ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @NonNull
    @Override
    public String getName() {
        return "AudioManage";
    }
    ///////////

    private AudioManager audioManager = null;
    private final int NOW_AUDIO_TYPE = AudioManager.STREAM_MUSIC;

    // 初始化
    @ReactMethod
    public void init(Context context) {
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    }

    /**
     * 最大音量
     */
    public int getSystemMaxVolume() {
        return audioManager.getStreamMaxVolume(NOW_AUDIO_TYPE);
    }

    /**
     * 最小音量
     */
    public int getSystemMinVolume() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            return audioManager.getStreamMinVolume(NOW_AUDIO_TYPE);
        } else {
            return 0;
        }
    }
    // 当前音量
    public int getSystemCurrentVolume() {
        return audioManager.getStreamVolume(NOW_AUDIO_TYPE);
    }

    /**
     * 获取当前的音量值(0-100)
     */
    @ReactMethod
    public void getCurrentVolume(Promise promise) {
        try {
            if (audioManager == null) {
                init(getReactApplicationContext());
            }
            int volume = 100 * getSystemCurrentVolume() / getSystemMaxVolume();
            promise.resolve(volume);
        } catch (RuntimeException e) {
            Event.logEmit("音量获取失败: " + e.getMessage());
            promise.resolve(null);
        }
    }

    /**
     * 调整音量(0-100)
     */
    @ReactMethod
    public void setCurrentVolume(int num, Promise promise) {
        try {
            if (audioManager == null) {
                init(getReactApplicationContext());
            }
            int a = (int) Math.ceil((num) * getSystemMaxVolume() * 0.01);
            a = Math.max(a, 0);
            a = Math.min(a, 100);
            audioManager.setStreamVolume(NOW_AUDIO_TYPE, a, AudioManager.FLAG_SHOW_UI);
            promise.resolve(null);
        } catch (RuntimeException e) {
            Event.logEmit("音量设置失败: " + e.getMessage());
            promise.resolve(e.getMessage());
        }
    }
}
